package com.smmisia.shop.event;

import com.smmisia.shop.entity.TradeOrder;
import com.smmisia.shop.request.OrderConfirmRequest;
import com.smmisia.shop.request.ProductTrySaleRequest;
import com.smmisia.shop.service.ProductService;
import com.smmisia.shop.service.TradeOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.smmisia.shop.constant.UserType.PLATFORM;

@Component
public class OrderEventListener {

    @Autowired
    private ProductService productService;

    @Autowired
    private TradeOrderService tradeOrderService;

    @EventListener(OrderCreateEvent.class)
    @Async("orderListenExecutor")
    public void onApplicationEvent(OrderCreateEvent event) {
        TradeOrder tradeOrder = (TradeOrder) event.getSource();
        ProductTrySaleRequest request = new ProductTrySaleRequest();
        request.setProductId(Long.valueOf(tradeOrder.getGoodsId()));
        request.setQuantity(Long.valueOf(tradeOrder.getItemCount()));
        request.setIdentifier(tradeOrder.getIdentifier());
        request.setOrderId(tradeOrder.getOrderId());
        Boolean result = productService.trySale(request);
        if (result){
            OrderConfirmRequest orderConfirmRequest = new OrderConfirmRequest();
            orderConfirmRequest.setIdentifier(tradeOrder.getIdentifier());
            orderConfirmRequest.setBuyerId(tradeOrder.getBuyerId());
            orderConfirmRequest.setProductId(request.getProductId());
            orderConfirmRequest.setItemCount(request.getQuantity());
            orderConfirmRequest.setOrderId(request.getOrderId());
            orderConfirmRequest.setOperateTime(new Date());
            orderConfirmRequest.setOperator(tradeOrder.getBuyerId());
            orderConfirmRequest.setOperatorType(PLATFORM.name());
            tradeOrderService.confirm(orderConfirmRequest);
        }
    }
}
